package com.dyava.dycache.autoconfigure;

import com.dyava.dycache.core.CacheDefined;
import com.dyava.dycache.core.CacheEngineManager;
import com.dyava.dycache.guava.GuavaCacheEngine;
import com.dyava.dycache.redis.RedisCacheEngine;
import com.dyava.dycache.simple_redis_client.SimpleRedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@ConditionalOnProperty(name="dycache.engine",havingValue = "true",matchIfMissing = true)
@Configuration
@EnableConfigurationProperties({DyCacheEngineProperties.class})
public class DycacheAutoConfigure {
    @Autowired
    DyCacheEngineProperties dyCacheEngineProperties;

    @Bean("dyRedisClient")
    @ConditionalOnMissingBean(name="dyRedisClient")
    SimpleRedisClient simpleRedisClient(){
        SimpleRedisClient simpleRedisClient = new SimpleRedisClient(dyCacheEngineProperties.getSimpleRedisClient().getName(),
                dyCacheEngineProperties.getSimpleRedisClient().getIp(),
                dyCacheEngineProperties.getSimpleRedisClient().getPort(),
                dyCacheEngineProperties.getSimpleRedisClient().getPassword(),
                dyCacheEngineProperties.getSimpleRedisClient().getDatabase());
        return simpleRedisClient;
    }

    @Bean("dyL2CacheEngine")
    @ConditionalOnMissingBean(name="dyL2CacheEngine")
    RedisCacheEngine redisCacheEngine(){
        RedisCacheEngine redisCacheEngine = new RedisCacheEngine();
        redisCacheEngine.setRedisClient(simpleRedisClient());
        redisCacheEngine.setName(dyCacheEngineProperties.getL2Name());
        return redisCacheEngine;
    }

    @Bean("dyL1CacheEngine")
    @ConditionalOnMissingBean(name="dyL1CacheEngine")
    GuavaCacheEngine guavaCacheEngine(){
        GuavaCacheEngine guavaCacheEngine = new GuavaCacheEngine();
        guavaCacheEngine.setName(dyCacheEngineProperties.getL1Name());
        return guavaCacheEngine;
    }

    @Autowired
    List<CacheDefined> cacheDefinedList = new ArrayList<>();


    @Bean("cacheEngineManager")
    @ConditionalOnMissingBean(name="cacheEngineManager")
    CacheEngineManager cacheEngineManager(){
        CacheEngineManager cacheEngineManager = new CacheEngineManager();
        cacheEngineManager.addCacheEngine(guavaCacheEngine());
        cacheEngineManager.addCacheEngine(redisCacheEngine());
        for(CacheDefined cacheDefined : cacheDefinedList){
            cacheEngineManager.addCacheDefined(cacheDefined);
        }
        return cacheEngineManager;
    }

}
